package com.omp.common.dao;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class CommonDAO extends HibernateDaoSupport {

	public void save(Object entity) {
		getHibernateTemplate().save(entity);
	}

	public void update(Object entity) {
		getHibernateTemplate().update(entity);
	}

	public void saveOrUpdate(Object entity) {
		getHibernateTemplate().saveOrUpdate(entity);
	}

	public void delete(Object entity) {
		getHibernateTemplate().delete(entity);
	}

	@SuppressWarnings("unchecked")
	public void deleteAll(Collection entities) {
		getHibernateTemplate().deleteAll(entities);
	}

	@SuppressWarnings("unchecked")
	public Object findById(final Class entity, final Serializable id) {
		if (id == null || "".equals(id)) {
			return null;
		} else {
			return getHibernateTemplate().get(entity, id);
		}
	}

	/**
	 * 在数据库中查询出该类的所有实体
	 * 
	 * @param Class entity 域模型对象.class
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List findAll(final Class entity) {
		return getHibernateTemplate().find("from " + entity.getName());
	}

	/**
	 * 在数据库中查询出该类的所有实体
	 * 
	 * @param Class entity 域模型对象.class
	 * @param String orderBy 排序字段
	 * @param String order 排序方向
	 * @return List
	 */
	@SuppressWarnings("unchecked")
	public List findAll(final Class entity, String orderBy, String order) {
		StringBuffer hql = new StringBuffer();
		hql.append("from ").append(entity.getName());
		if (StringUtils.isNotBlank(orderBy)) {
			hql.append(" order by ").append(orderBy);
			if (StringUtils.isNotBlank(order)) {
				hql.append(" ").append(order);
			}
		}
		return getHibernateTemplate().find(hql.toString());
	}
}
